package com.getword.service.impl;

import com.getword.domain.Reply;
import com.getword.domain.VideoComment;
import com.getword.mongodao.VideoCommentRepository;
import com.getword.service.VideoCommentService;
import com.getword.web.model.Result;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
//@Transactional
public class VideoCommentServiceImpl implements VideoCommentService {
    @Autowired
    private VideoCommentRepository videoCommentRepository;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Result saveComment(VideoComment comment) {
        VideoComment save = videoCommentRepository.save(comment);
        return Result.success(save);
    }

    @Override
    public Result addReply(Reply reply, String commentId) {
        VideoComment videoComment = videoCommentRepository.findVideoCommentById(commentId);
        List<Reply> replyList = videoComment.getReplyList();
        if(replyList == null){
            replyList = new ArrayList<>();
        }
        replyList.add(reply);
        Criteria where = Criteria.where("id").is(commentId);
        Query query = Query.query(where);
        Update update = Update.update("replyList", replyList);
        UpdateResult result = mongoTemplate.updateFirst(query, update, VideoComment.class);
        if(result.getModifiedCount() >0){
            return Result.success(reply);
        }
        return Result.fail("添加失败");
    }

    @Override
    public Result getCommentsByVideoId(String videoId) {
        List<VideoComment> comments = videoCommentRepository.findVideoCommentsByVideoId(videoId);
        return Result.success(comments);
    }
}
